import json

from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.http import JsonResponse, HttpResponseBadRequest, HttpResponseNotFound, HttpResponseServerError
from django.shortcuts import get_object_or_404
from django.db.models import Q
from django.utils import timezone
from .models import Conversation, Message, ConversationParticipant, UserStatus
from .serializers import (
    ConversationSerializer, MessageSerializer,
    UserStatusSerializer, StudentSerializer, TeacherSerializer
)
from accounts.models import Student, Teacher
from accounts.jwt_utils import jwt_required
from django.http import JsonResponse

@require_http_methods("GET")
@jwt_required
def conversation_list(request):
    """获取当前用户的所有会话"""
    print("conversation_list")
    user_type = request.user_type
    user_id = request.user_id

    # 确定用户类型
    if user_type =='student':
        user_obj = Student.objects.get(id=user_id)
    elif user_type == 'teacher':
        user_obj = Teacher.objects.get(id=user_id)
    else:
        return JsonResponse({'error': '无效的用户类型'}, status=400)

    # 获取用户参与的会话
    if user_type == 'student':
        conversations = Conversation.objects.filter(
            conversationparticipant__student=user_obj,
            conversationparticipant__user_type='student'
        ).distinct().order_by('-updated_at')
    else:
        conversations = Conversation.objects.filter(
            conversationparticipant__teacher=user_obj,
            conversationparticipant__user_type='teacher'
        ).distinct().order_by('-updated_at')

    serializer = ConversationSerializer(conversations, many=True, context={'request': request})
    return JsonResponse(serializer.data, status=200, safe=False)

@csrf_exempt
@require_http_methods(["POST"])
@jwt_required
def conversation_create(request):
    """创建新会话"""
    data = json.loads(request.body)
    other_user_id = data.get('user_id')
    other_user_type = data.get('user_type')  # 'student' 或 'teacher'

    if not other_user_id or not other_user_type:
        return JsonResponse({'error': '需要指定对方用户ID和用户类型'}, status=400)

    # 获取当前用户
    user_type = request.user_type  # 从jwt_required装饰器中获取
    user_id = request.user_id
    print(f"current_user:{user_id}")
    print(f"user_type:{user_type}")
    print(f"other_user:{other_user_id}")
    print(f"other_type:{other_user_type}")


    if user_type =='student':
        current_user_type = 'student'
        current_user_obj = Student.objects.get(id=user_id)
    elif user_type == 'teacher':
        current_user_type = 'teacher'
        current_user_obj = Teacher.objects.get(id=user_id)
    else:
        return JsonResponse({'error': '无效的用户类型'}, status=400)

    # 获取对方用户
    try:
        if other_user_type == 'student':
            other_user = Student.objects.get(id=other_user_id)
            other_user_obj = Student.objects.get(id=other_user_id)
        else:
            other_user = Teacher.objects.get(id=other_user_id)
            other_user_obj = Teacher.objects.get(id=other_user_id)
    except (Student.DoesNotExist, Teacher.DoesNotExist):
        return JsonResponse({'error': '找不到指定用户'}, status=400)

    # 检查是否已存在会话
    if current_user_type == 'student':
        conversation = Conversation.objects.filter(
            conversationparticipant__student=current_user_obj,
            conversationparticipant__user_type='student'
        ).filter(
            Q(conversationparticipant__teacher=other_user,
              conversationparticipant__user_type='teacher') if other_user_type == 'teacher' else
            Q(conversationparticipant__student=other_user, conversationparticipant__user_type='student')
        ).first()
    else:
        conversation = Conversation.objects.filter(
            conversationparticipant__teacher=current_user_obj,
            conversationparticipant__user_type='teacher'
        ).filter(
            Q(conversationparticipant__teacher=other_user,
              conversationparticipant__user_type='teacher') if other_user_type == 'teacher' else
            Q(conversationparticipant__student=other_user, conversationparticipant__user_type='student')
        ).first()
    if conversation:
        # 如果已存在会话，直接返回
        print("已存在会话，直接返回")
        serializer = ConversationSerializer(conversation, context={'request':request})
        return JsonResponse(serializer.data, status=200)

    # 创建新会话
    conversation = Conversation.objects.create()
    print(f"current_user_obj:{current_user_obj}")
    print(f"other_user_obj:{other_user_obj}")
    # 添加当前用户作为参与者
    ConversationParticipant.objects.create(
        conversation=conversation,
        student=current_user_obj if current_user_type == 'student' else None,
        teacher=current_user_obj if current_user_type == 'teacher' else None,
        user_type=current_user_type
    )

    # 添加对方用户作为参与者
    ConversationParticipant.objects.create(
        conversation=conversation,
        student=other_user if other_user_type == 'student' else None,
        teacher=other_user if other_user_type == 'teacher' else None,
        user_type=other_user_type
    )
    print("serializer之前")
    serializer = ConversationSerializer(conversation, context={'request': request})
    print(f"serializer:{serializer}")
    return JsonResponse(serializer.data, status=201)


def conversation_detail(request, pk):
    """获取会话详情（示例，可根据需求扩展）"""
    conversation = get_object_or_404(Conversation, id=pk)
    serializer = ConversationSerializer(conversation)
    return JsonResponse(serializer.data)

@require_http_methods("POST")
@jwt_required
def conversation_messages(request, pk=None):
    # print("获取消息")
    session_id = json.loads(request.body).get('session_id')
    """获取会话中的消息"""
    conversation = get_object_or_404(Conversation, id=session_id)
    user_id = request.user_id
    user_type = request.user_type
    # 确定用户类型
    try:
        if user_type == 'student':
            user_obj = Student.objects.get(id=user_id)
        elif user_type == 'teacher':
            user_obj = Teacher.objects.get(id=user_id)
        else:
            return JsonResponse({'error': '无效的用户类型'}, status=400)
    except (Student.DoesNotExist, Teacher.DoesNotExist):
        return JsonResponse({'error': '找不到当前用户'}, status=400)


    # 确保用户是会话参与者
    is_participant = False
    if user_type == 'student':
        is_participant = conversation.conversationparticipant_set.filter(
            student=user_obj,
            user_type='student'
        ).exists()
    else:
        is_participant = conversation.conversationparticipant_set.filter(
            teacher=user_obj,
            user_type='teacher'
        ).exists()

    if not is_participant:
        return JsonResponse({'error': '没有权限访问此会话'}, status=403)

    # 标记消息为已读
    try:
        if user_type == 'student':
            participant = conversation.conversationparticipant_set.get(
                student=user_obj,
                user_type='student'
            )
        else:
            participant = conversation.conversationparticipant_set.get(
                teacher=user_obj,
                user_type='teacher'
            )

        participant.unread_messages = 0
        participant.last_read_at = timezone.now()
        participant.save()
    except ConversationParticipant.DoesNotExist:
        print('participant does not exist')
        return JsonResponse({'error': '会话参与者不存在'})

    # 获取消息
    messages = conversation.messages.order_by('created_at')
    serializer = MessageSerializer(messages, many=True, context={'request': request})
    return JsonResponse(serializer.data, safe=False, status=200)

@jwt_required
def conversation_search(request):
    """搜索用户并创建会话"""
    data = json.loads(request.body)
    query = data.get('query')
    user_type = data.get('user_type')
    print(f"query:{query}")
    print(f"user_type:{user_type}")

    # 搜索用户
    if user_type == 'student':
        users = Student.objects.filter(
            Q(name__icontains=query) |
            Q(student_id__icontains=query)
        )
    elif user_type == 'teacher':
        users = Teacher.objects.filter(
            Q(name__icontains=query) |
            Q(teacher_id__icontains=query)
        )
    else:
        # 如果未指定类型，搜索所有用户
        students = Student.objects.filter(
            Q(name__icontains=query) |
            Q(student_id__icontains=query)
        )
        teachers = Teacher.objects.filter(
            Q(name__icontains=query) |
            Q(teacher_id__icontains=query)
        )
        return JsonResponse({
            'students': StudentSerializer(students, many=True).data,
            'teachers': TeacherSerializer(teachers, many=True).data
        })

    serializer = StudentSerializer(users, many=True) if user_type == 'student' else TeacherSerializer(users, many=True)
    return JsonResponse(serializer.data, safe=False, status=200)

@csrf_exempt
@jwt_required
def message_create(request):
    """发送新消息"""
    data = json.loads(request.body)
    conversation_id = data.get('conversation_id')
    content = data.get('content')
    print(f"conversation_id:{conversation_id}")
    print(f"content:{content}")
    if not conversation_id or not content:
        return JsonResponse({'error': '需要指定会话ID和消息内容'}, status=400)

    conversation = get_object_or_404(Conversation, id=conversation_id)

    # 获取当前用户
    user_type = request.user_type  # 从jwt_required装饰器中获取
    user_id = request.user_id
    print(f"user_type:{user_type}")


    try:
        if user_type == 'student':
            user_obj = Student.objects.get(id=user_id)
        elif user_type == 'teacher':
            user_obj = Teacher.objects.get(id=user_id)
        else:
            return JsonResponse({'error': '无效的用户类型'}, status=400)
    except (Student.DoesNotExist, Teacher.DoesNotExist):
        return JsonResponse({'error': '找不到当前用户'}, status=400)

    # 确保用户是会话参与者
    is_participant = False
    if user_type == 'student':
        is_participant = conversation.conversationparticipant_set.filter(
            student=user_obj,
            user_type='student'
        ).exists()
    else:
        is_participant = conversation.conversationparticipant_set.filter(
            teacher=user_obj,
            user_type='teacher'
        ).exists()

    if not is_participant:
        return JsonResponse({'error': '没有权限在此会话中发送消息'}, status=403)

    # 创建消息
    if user_type == 'student':
        message = Message.objects.create(
            conversation=conversation,
            sender_student=user_obj,
            content=content
        )
    else:
        message = Message.objects.create(
            conversation=conversation,
            sender_teacher=user_obj,
            content=content
        )

    # 更新会话的最后更新时间
    conversation.updated_at = timezone.now()
    conversation.save()

    # 更新其他参与者的未读消息计数
    other_participants = conversation.conversationparticipant_set.exclude(
        Q(student=user_obj, user_type='student') if user_type == 'student' else
        Q(teacher=user_obj, user_type='teacher')
    )

    for participant in other_participants:
        participant.unread_messages += 1
        participant.save()

    serializer = MessageSerializer(message)
    return JsonResponse(serializer.data, status=201)

@jwt_required
def user_status_me(request):
    """获取当前用户的状态"""
    user_id = request.user_id
    user_type = request.user_type
    print(f"user_id:{user_id}")
    print(f"user_type:{user_type}")
    # 确定用户类型
    if user_type == 'student':
        try:
            user = Student.objects.get(id=user_id)
            status = UserStatus.objects.get(student=user)
            serializer = UserStatusSerializer(status)
            return JsonResponse(serializer.data, safe=False, status=200)
        except UserStatus.DoesNotExist:
            return JsonResponse({'error': '用户状态不存在'}, status=404)
    elif user_type == 'teacher':
        try:
            user = Teacher.objects.get(id=user_id)
            status = UserStatus.objects.get(teacher=user)
            serializer = UserStatusSerializer(status)
            return JsonResponse(serializer.data, safe=False, status=200)
        except UserStatus.DoesNotExist:
            return JsonResponse({'error': '用户状态不存在'}, status=404)

    return JsonResponse({'error': '无效的用户类型'}, status=400)